<?php

namespace Console;

use DuAdmin\Components\Crontab;
use DuAdmin\Helpers\AppHelper;
use DuAdmin\Models\Cron;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
use Yii;
use yii\console\Controller;

class ScheduleController extends Controller
{

    public function actionIndex()
    {
        Yii::debug("prepare cron");
        if ($tasks = Cron::findAll([
            'isActive' => true,
            'isOk' => true
        ])) {

            $phpBinaryFinder = new PhpExecutableFinder();
            $phpBinaryPath = $phpBinaryFinder->find();
            $processes = [];
            $isWindow = $this->isWindowOS();
            foreach ($tasks as $task) {
                $time = null;
                try {
                    $time = Crontab::parse($task->mhdmd);
                } catch (\InvalidArgumentException $e) {
                    Yii::error('任务的cron表达式格式不正确,' . $e->getMessage(), __METHOD__);
                    Yii::error($e->getTraceAsString(), __METHOD__);
                    continue;
                }
                $cur = time();
                if (\intval($time) <= $cur) {
                    //可执行的定时任务
                    $process = new Process([$phpBinaryPath, 'yii', 'schedule/run', $task->id, '>/dev/null', '2>&1', $isWindow ? ';' : '&'], Yii::$app->basePath);
                    $process->start();
                    $processes[] = $process;
                }
            }
            $loop = true;
            while ($loop) {
                $loop = false;
                foreach ($processes as $process) {
                    if ($process->isRunning()) {
                        $loop = true;
                    }
                }
            }
        }
    }

    public function actionRun($taskId)
    {
        $task = Cron::findOne($taskId);
        $cur = time();
        // 更新任务的执行时间
        $task->runAt = date('Y-m-d H:i:s', $cur);
        $task->save(false);
        $class = $task->jobScript;
        if (class_exists($class)) {
            $instance = Yii::createObject($class);
            $instance->handle(AppHelper::parseText2Assoc($task->param), $task);
            $task->isOk = true;
        } else {
            $task->isOk = false;
            $task->errorMsg = '脚本不存在';
        }
        $task->save(false);
    }

    protected function isWindowOS()
    {
        if (PATH_SEPARATOR == ':') return false;
        else return true;
    }
}
